import pygame
import data
import entities
import gamestate as gs_module
import gfx
import ui_backend


COLKEY_TRANSPARENT = (255, 0, 255)


def load_img(filename, hasTransparency=False):
    img = pygame.image.load(data.filepath(filename)).convert()
    if hasTransparency: img.set_colorkey(COLKEY_TRANSPARENT)
    return img

def create_reactors():
    decals = (
        load_img("decal1.png"),
        load_img("decal2.png"),
        load_img("decal3.png"),
        load_img("decal4.png")
    )
    
    base_reactors = (
        load_img("reactor.png"),
        load_img("reactor_light_damage.png"),
        load_img("reactor_heavy_damage.png"),
        load_img("reactor_destroyed.png")
    )
    def apply_decal(base, decal):
        variant = base.copy()
        variant.blit(decal, (121, 104))
        return variant
    
    def create_variants(decal):
        return [apply_decal(base, decal) for base in base_reactors]
    return [create_variants(decal) for decal in decals]

def create_background():
    bg = load_img("bg.png")
    generator = load_img("generator.png")
    bg.blit(generator, (25, 250))
    bg.blit(generator, (420, 250))
    return bg
    
def initialize_on_startup():
    global bg
    global reactors

    bg = create_background()
    
    reactorImages = create_reactors()
    
    reactorPositions = (
        (48, 275),
        (218, 308),
        (444, 308),
        (615, 308)
    )
    
    reactors = [entities.ReactorBuilding(imgs, pos) for imgs, pos in zip(reactorImages, reactorPositions)]
    
    global img_worker_unprotected
    global img_worker_protected
    global img_firefighter
    global img_copterImage
    global img_waterFromCopterImage
    
    img_worker_unprotected = load_img("worker_unprotected.png", True)
    img_worker_protected = load_img("worker_protected.png", True)
    img_firefighter = load_img("firefighter.png", True)
    img_copterImage = load_img("helicopter.png", True)
    img_waterFromCopterImage = load_img("water_from_helicopter.png", True)
    
    

def initialize_for_new_game():
    global gamestate
    
    gamestate = gs_module.GameState()
    for reactor in reactors: reactor.set_state(0)
    
    # TODO (all of the below)
    global helicopter
    global worker
    
    workerSprite = gfx.SpriteSheet(img_firefighter, 16, 16)
    worker = entities.SingleWorker(workerSprite, (400, 100))
    worker.move_to((500, 700))
    copterSprite = gfx.SpriteSheet(img_copterImage, 226, 228)
    waterFromCopterSprite = gfx.SpriteSheet(img_waterFromCopterImage, 240, 140)
    helicopter = entities.Helicopter(copterSprite, waterFromCopterSprite, (0, 10))
    

def draw_action_box(action, isHovered):
    if isHovered:
        pygame.draw.rect(ui_backend.screen, ui_backend.ELEMENTACTIVE, action.rect, ui_backend.OUTLINE)
    else:
        pygame.draw.rect(ui_backend.screen, ui_backend.ELEMENTIDLE, action.rect, ui_backend.OUTLINE)
    
